package arithmetic.someAlgorithm;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * 用Callable和Future实现的线程方式实例
 * @author lidd
 *
 */
public class ThreadDemo {

	/*public static void main(String[] args) {
		Callable<Integer> callable = new Callable<Integer>() {
			public Integer call(){
				return new Random().nextInt(100);
			}
		};
		FutureTask<Integer> future = new FutureTask<Integer>(callable);
		new Thread(future).start();
		try {
			Thread.sleep(500);
			System.out.println(future.get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/

	/*public static void main(String[] args) {
		ExecutorService threadpool = Executors.newSingleThreadExecutor();
		Callable<Integer> callable = new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {

				return new Random().nextInt(100);
			}
		};
		Future<Integer> task = threadpool.submit(callable);
		try {
			Thread.sleep(500);
			System.out.println(task.get());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}*/

    /*public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
        for(int i = 1; i < 5; i++) {
            final int taskID = new Random().nextInt(100);
            cs.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    return taskID;
                }
            });
        }
        // 可能做一些事情
        for(int i = 1; i < 5; i++) {
            try {
                System.out.println(cs.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }*/
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        List<Future<Integer>> list = new ArrayList<Future<Integer>>();
        Future<Integer> future = null;
        for(int i = 0; i < 4; i++) {
            final int taskID = new Random().nextInt(100);
            future = threadPool.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    return taskID;
                }
            });
            list.add(future);
        }
        // 可能做一些事情
        for(int i = 0; i < 4; i++) {
            try {
                System.out.println(list.get(i).get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
